package map_func

import (
	"fmt"
	"sync"
)

type Item struct {
	Name  string
	Value string
}

type MTestMap struct {
	Map  map[int]string
	Lock *sync.RWMutex
}

// MTestMapSet 自定义线程安全map
func (m *MTestMap) MTestMapSet(key int, value string) {
	m.Lock.Lock()
	defer m.Lock.Unlock()
	m.Map[key] = value
}

// MTestMapGet ...
func (m *MTestMap) MTestMapGet(key int) string {
	m.Lock.RLock()
	defer m.Lock.RUnlock()
	return m.Map[key]
}

// MTestMapDelete ...
func (m *MTestMap) MTestMapDelete(key int) {
	m.Lock.Lock()
	defer m.Lock.Unlock()
	delete(m.Map, key)
}

func MapRange() error {
	defer func() {
		//fmt.Println("退出前处理1")
	}()
	defer func() {
		//fmt.Println("退出前处理2")
	}()
	testMap := make(map[string]Item, 0)
	testMap["m1"] = Item{"张三", "200"}
	testMap["m2"] = Item{"李四", "250"}
	testMap["m3"] = Item{"王五", "300"}

	for key, item := range testMap {
		fmt.Sprintf("key(%s), item(%s-%s)\n", key, item.Name, item.Value)
	}
	return nil
}

func MTestMapAdd(data string, n int) {
	testMap := &MTestMap{
		Map:  make(map[int]string, 1000),
		Lock: new(sync.RWMutex),
	}
	for i := 0; i < n; i++ {
		testMap.MTestMapSet(i, data)
	}
}

func MSyncMapAdd(data string, n int) {
	testMap := sync.Map{}
	for i := 0; i < n; i++ {
		testMap.Store(n, data)
	}
}